<?php
// +----------------------------------------------------------------------
// | 控制器 - ADMIN - 模板
// +----------------------------------------------------------------------
declare(strict_types=1);

namespace app\controller\admin;

use OpenApi\Annotations as OA;
use app\BaseController;
use app\model\SystemUsersMessagesModel;
use think\db\Query;
use think\Response;

/**
 * 系统消息（用户）
 *
 * Class Messages
 * @package app\controller\admin
 */
class Messages extends BaseController
{

    /**
     * @OA\Post(
     *   path="/api/admin/messages/page",
     *   tags={"系统消息"},
     *   summary="获取分页列表",
     *   @OA\RequestBody(
     *   @OA\MediaType(
     *     mediaType="content-type/json",
     *       @OA\Schema(
     *         @OA\Property(description="当前页", property="page", type="integer", example="1"),
     *         @OA\Property(description="分页数量", property="pageSize", type="integer", example="10"),
     *         @OA\Property(description="标题检索", property="title", type="string", example=""),
     *         @OA\Property(description="已读检索，可传入true或false", property="isRead", type="string", example=""),
     *         @OA\Property(
     *           description="时间检索范围，数组第一项为开始时间，第二项为结束时间",
     *           property="time",
     *           type="array",
     *           items={
     *             @OA\Items(type="string", format="date-time")
     *           },
     *           example={"2000-01-01", "2099-12-31"}
     *         ),
     *         required={"page","pageSize"})
     *     )
     *   ),
     *   security={{"bearerAuth":{}}},
     *   @OA\Response(response=401, description="未携带TOKEN或已过期"),
     *   @OA\Response(
     *     response="200",
     *     description="Success",
     *     @OA\JsonContent(
     *       type="object",
     *       @OA\Property(property="success", type="boolean", example=true),
     *       @OA\Property(property="message", type="string", example="操作成功"),
     *       @OA\Property(
     *         property="data",
     *         type="object",
     *         @OA\Property(property="total", type="integer", example="100"),
     *         @OA\Property(property="currentPage", type="integer", example="1"),
     *         @OA\Property(property="pageSize", type="integer", example="10"),
     *         @OA\Property(
     *           property="list",
     *           type="array",
     *           @OA\Items(ref="#/components/schemas/SystemUsersMessages")
     *         )
     *       )
     *     )
     *   )
     * )
     * @return Response
     */
    public function getPageList(): Response
    {
        // 处理查询数据
        $search = [
            'title' => $this->request->post('title'),
            'isRead' => $this->request->post('isRead'),
            'time' => $this->request->post('time'),
        ];
        $list = SystemUsersMessagesModel::queryOrder()->withSearch(array_keys($search), $search)->paginate([
            'list_rows' => $this->request->post('pageSize', 10),
            'page' => $this->request->post('page', 1),
        ])->toArray();
        return $this->response([
            'list' => $list['data'],
            'total' => $list['total'],
            'currentPage' => $list['current_page'],
            'pageSize' => $list['per_page'],
        ]);
    }

    /**
     * @OA\Put(
     *   path="/api/admin/messages/{id}/read",
     *   tags={"系统消息"},
     *   summary="标记已读状态",
     *   @OA\Parameter(name="id", in="path", required=true,@OA\Schema(type="integer")),
     *   @OA\RequestBody(
     *     required=true,
     *     @OA\JsonContent(
     *       type="object",
     *       @OA\Property(property="read", type="boolean", example=true),
     *     )
     *   ),
     *   security={{"bearerAuth":{}}},
     *   @OA\Response(response=401, description="未携带TOKEN或已过期"),
     *   @OA\Response(
     *     response="200",
     *     description="Success",
     *     @OA\JsonContent(
     *       type="object",
     *       @OA\Property(property="success", type="boolean", example=true),
     *       @OA\Property(property="message", type="string", example="操作成功"),
     *       @OA\Property(
     *         property="data",
     *         type="object",
     *         ref="#/components/schemas/SystemUsersMessages"
     *       )
     *     )
     *   )
     * )
     * @return Response
     */
    public function setRead(): Response
    {
        $uid = $this->request->getUserId();
        $id = $this->request->route('id');
        $isRead = $this->request->post('read');

        $data = SystemUsersMessagesModel::withSearch(
            ['uid'],
            ['uid' => $uid]
        )->find($id);
        if (!$data) {
            abort(404, '数据未找到');
        }
        // 数据更新
        $data->save([
            'isRead' => $isRead
        ]);
        // 返回新数据
        return $this->response($data->toArray());
    }

    /**
     * @OA\Put(
     *   path="/api/admin/messages/read",
     *   tags={"系统消息"},
     *   summary="全部已读",
     *   description="将用户所有系统消息标记为已读状态",
     *   security={{"bearerAuth":{}}},
     *   @OA\Response(response=401, description="未携带TOKEN或已过期"),
     *   @OA\Response(
     *     response="200",
     *     description="Success",
     *     @OA\JsonContent(
     *       type="object",
     *       @OA\Property(property="success", type="boolean", example=true),
     *       @OA\Property(property="message", type="string", example="操作成功"),
     *       @OA\Property(
     *         property="data",
     *         type="object",
     *         ref="#/components/schemas/SystemUsersMessages"
     *       )
     *     )
     *   )
     * )
     * @return Response
     */
    public function setReadAll(): Response
    {
        $uid = $this->request->getUserId();
        $ids = SystemUsersMessagesModel::withSearch(
            ['uid'],
            ['uid' => $uid]
        )->column('id');
        if ($ids) {
            // 批量已读
            $data = array_map(fn($value): array => ['id' => $value, 'isRead' => true], $ids);
            (new SystemUsersMessagesModel)->saveAll($data);
        }
        return $this->response();
    }

    /**
     * @OA\Delete(
     *   path="/api/admin/messages/{id}",
     *   tags={"系统消息"},
     *   summary="删除信息",
     *   @OA\Parameter(name="id", in="path", required=true, @OA\Schema(type="integer")),
     *   security={{"bearerAuth":{}}},
     *   @OA\Response(response=401, description="未携带TOKEN或已过期"),
     *   @OA\Response(
     *     response="200",
     *     description="Success",
     *     @OA\JsonContent(
     *       type="object",
     *       @OA\Property(property="success", type="boolean", example=true),
     *       @OA\Property(property="message", type="string", example="操作成功"),
     *       @OA\Property(
     *         property="data",
     *         example=null
     *       )
     *     )
     *   )
     * )
     * @return Response
     */
    public function delete(): Response
    {
        $uid = $this->request->getUserId();
        $id = $this->request->route('id');
        $data = SystemUsersMessagesModel::withSearch(
            ['uid'],
            ['uid' => $uid]
        )->find($id);
        if (!$data) {
            abort(404, '数据未找到');
        }
        $data->delete();
        return $this->response();
    }

    /**
     * @OA\Delete(
     *   path="/api/admin/messages",
     *   tags={"系统消息"},
     *   summary="批量删除信息",
     *   @OA\RequestBody(
     *   @OA\MediaType(
     *     mediaType="content-type/json",
     *       @OA\Schema(
     *         @OA\Property(
     *           description="指定的id",
     *           property="ids",
     *           type="array",
     *           items={@OA\Items(type="integer")},
     *           example={1, 2}
     *         ),
     *         required={"ids"})
     *     )
     *   ),
     *   security={{"bearerAuth":{}}},
     *   @OA\Response(response=401, description="未携带TOKEN或已过期"),
     *   @OA\Response(
     *     response="200",
     *     description="Success",
     *     @OA\JsonContent(
     *       type="object",
     *       @OA\Property(property="success", type="boolean", example=true),
     *       @OA\Property(property="message", type="string", example="操作成功"),
     *       @OA\Property(property="data", example=null)
     *     )
     *   )
     * )
     * @return Response
     */
    public function batchDelete(): Response
    {
        $uid = $this->request->getUserId();
        $ids = $this->request->delete('ids');
        if (!$ids || !is_array($ids)) {
            abort(404, '数据未找到');
        }
        SystemUsersMessagesModel::destroy(function (Query $query) use ($uid, $ids) {
            $query->withSearch(
                ['uid', 'ids'],
                ['uid' => $uid, 'ids' => $ids]
            );
        });
        return $this->response();
    }
}
